package com.sky.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private RedisTemplate redisTemplate;




    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void addDish(DishDTO dishDTO) {
        //新增dish表字段 但是没有菜品风味属性
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        //通过请求实体拿到口味属性数据集合

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null) {
            for (DishFlavor flavor : flavors) {
                //菜品和风味一对多关联id
                flavor.setDishId(dish.getId());
            }
        }
        dishFlavorMapper.insertBatch(flavors);


    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult getPage(DishPageQueryDTO dishPageQueryDTO) {
        //开启分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //调用查询数据
        Page<DishVO> dishList = dishMapper.getPage(dishPageQueryDTO);
        //将数据封装到响应结果类
        PageResult pageResult = new PageResult();
        pageResult.setRecords(dishList.getResult());
        pageResult.setTotal(dishList.getTotal());

        return pageResult;
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    @Transactional
    public void delete(List<Long> ids) {
        //1.首先要明白一点,起售的状态下是无法删除该菜品的 所以需要获取到菜品的状态
        int count = dishMapper.getCountStatus(ids, StatusConstant.ENABLE);
        //2.如果查询到数据的状态包含起售就抛出异常
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //3.查询要删除的菜品是否被套餐中间表关联
        int count2 = dishMapper.getCountSetmeal(ids);
        //4.如果有抛出异常
        if (count2 > 0) {
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }
        //删除菜品信息
        dishMapper.deleteById(ids);
        //删除对应风味信息
        dishFlavorMapper.deleteByfalvorId(ids);


    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {

        //方法一分开查询
        //1.首先查询dish表
        Dish dish  =  dishMapper.getById(id);
        //2.在通过dish_id查询 falavor字段
        List<DishFlavor> flavors =  dishFlavorMapper.getByDish(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
            dishVO.setFlavors(flavors);
        return dishVO;

        //方法二 关联查询 对sql要求更高 显示内连接 可能会查询到多条重复数据

        //return dishMapper.getByIdWithFlavor(id);
    }

    @Override
    public void updateDishWithFlavor(DishDTO dishDTO) {
        //1.首先修改dish表中的数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateDishWithFlavor(dish);
        //2.根据dishDTO中的id对应dish_id删除dish_flavor中所有相关数据
        dishFlavorMapper.deleteByfalvorId(Arrays.asList(dishDTO.getId()));
        //3.再将请求过来的菜品信息集合用DishFlavor实体封装再进行菜品表的
        //绑定设置关联id也就是dish_id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size()>0) {
            for (DishFlavor flavor : flavors) {
                //菜品和风味一对多关联id 向口味表插入n条数据
                flavor.setDishId(dish.getId());
            }
        }
        dishFlavorMapper.insertBatch(flavors);


    }

    /**
     * 管理端
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        // 查询categoryId分类下启售状态的菜品
        return dishMapper.getByCategoryId(categoryId, StatusConstant.ENABLE);
    }

    /**
     * 根据分类id查询菜品（以及对应的口味信息）
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        // 1. 从redis中获取缓存数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        List<DishVO> list = (List<DishVO>) valueOperations.get("dish_category_" + dish.getCategoryId());
        // 2. 没有获取到，则查询数据库
        if (list == null) {
            List<Dish> dishList = dishMapper.getByCategoryId(dish.getCategoryId(),dish.getStatus());

            list = new ArrayList<>();

            for (Dish d : dishList) {
                DishVO dishVO = new DishVO();
                BeanUtils.copyProperties(d,dishVO);

                //根据菜品id查询对应的口味
                List<DishFlavor> flavors = dishFlavorMapper.getByDish(d.getId());

                dishVO.setFlavors(flavors);
                list.add(dishVO);
            }
            // 3. 将数据存储到redis中
            valueOperations.set("dish_category_"+dish.getCategoryId(),list);
            log.info("查询数据库，缓存菜品数据...");
        }
        // 4. 如果获取到了redis的缓存数据，直接返回即可
        log.info("返回菜品数据...");
        return list;
    }

}